﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace SDT.Libraries.Utilities
{
    public class Utility
    {

        private static string RegExprIMG = @"(?<=img\s+([^>]+\s+)?src\=[\x27\x22])(?<1>[^\x27\x22]*)(?=[\x27\x22])";

        /// <summary>
        /// Ex : baseURL http://www.xxx.com
        /// Case 1 : url =/image/pic.jpg Result: http://www.xxx.com/image/pic.jpg
        /// Case 2 : url = http://vnexpress.net/image/pic.jpg Result: http://vnexpress.net/image/pic.jpg
        /// </summary>
        /// <param name="url"></param>
        /// <param name="baseUrl"></param>
        /// <returns></returns>
        private static string ConvertToAbsoluteUrl(string url, string baseUrl)
        {
            // we try to prevent the exception caused in the case the url is relative
            // (no scheme info) just for speed
            if (url.IndexOf(Uri.SchemeDelimiter) < 0 && baseUrl != null)
            {
                try
                {
                    Uri baseUri = new Uri(baseUrl);
                    return new Uri(baseUri, url).OriginalString;
                }
                catch
                {
                    return null;
                }
            }

            try
            {
                Uri uri = new Uri(url);
                return uri.OriginalString;
            }
            catch (Exception)
            {
                if (baseUrl != null)
                {
                    try
                    {
                        Uri baseUri = new Uri(baseUrl);
                        return new Uri(baseUri, url).AbsolutePath;
                    }
                    catch (Exception)
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
        }

        public static IList<string> GetUrlAttributeSrc(string baseUrl, string html)
        {
            Regex regExpr = new Regex(RegExprIMG);
            var l = new List<string>();

            for (Match m = regExpr.Match(html); m.Success; m = m.NextMatch())
            {
                string url = m.Groups[1].ToString();

                try
                {
                    url = ConvertToAbsoluteUrl(url, baseUrl);
                }
                catch (Exception)
                {
                }

                if (url != null)
                {
                    l.Add(url);
                }
            }
            return l;
        }

        public static string GetUrlSrc(string baseUrl, string html)
        {
            Regex regExpr = new Regex(RegExprIMG);
            Match n = regExpr.Match(html);
            // Ngày 20/09/2011 : Nguyên bản chỉ có trong vòng for
            // Thêm trường hợp m.Success = false (trong thẻ img không đc định dạng khớp với RegExpr.Math(html))
             if (n.Success)   // Việt Thêm  // Vietlv
             {
                for (Match m = regExpr.Match(html); m.Success; m = m.NextMatch())
                {
                    string url = m.Groups[1].ToString();

                    try
                    {
                        url = ConvertToAbsoluteUrl(url, baseUrl);
                    }
                    catch (Exception)
                    {
                    }

                    if (url != null)
                    {
                        return url;
                    }
                }
            
            }
            else
            {
               
                int startIndex = html.IndexOf("src");
                int endIndex = 0;
                var listHtml = html.ToCharArray();
                if (startIndex > 0)
                {
                    for (int i = startIndex; i <= html.Length; i++)
                    {
                        if ((listHtml[i + 1] == ' ') && (listHtml[i] == '"') && ((listHtml[i - 1] == 'g') || (listHtml[i - 1] == 'f') || (listHtml[i - 1] == 'n')))
                        {
                            endIndex = i;
                            break;
                        }
                    }
                    string newHtml = html.Substring(startIndex, endIndex - startIndex);
                    newHtml = newHtml.Replace('"', ' ');
                    newHtml = newHtml.Replace('=', ' ');
                    newHtml = newHtml.Replace("src", "");
                    newHtml = newHtml.Trim();
                    return newHtml;
                }
                
            }

            

            return string.Empty;
        }
        private static IList<string> GetUrlAttributeSrc(Regex regExpr, string baseUrl, string html)
        {
            var l = new List<string>();

            for (Match m = regExpr.Match(html); m.Success; m = m.NextMatch())
            {
                string url = m.Groups[1].ToString();

                try
                {
                    url = ConvertToAbsoluteUrl(url, baseUrl);
                }
                catch (Exception)
                {
                }

                if (url != null)
                {
                    l.Add(url);
                }
            }
            return l;
        }

        public static string GenNameImage(string url)
        {
            string[] ExtArray = { ".gif", ".jpg", ".doc", ".zip", ".pdf" };

            foreach (string ext in ExtArray)
                if (url.ToLower().EndsWith(ext) == true)
                    return string.Empty;

            string sName = DateTime.Now.ToLongDateString();
            return sName;

        }

       

     


    }
}
